package com.hw8.intercept;

import com.ehw8.base.domain.pojo.TokenItem;
import com.google.gson.Gson;
import com.hw8.utils.ErrorEnum;
import com.hw8.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class RequestAspect {

    @Around(value = "execution(* com.hw8.controller..*(..))")
    public Object assertAround(ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        TokenItem tokenItem = JWTUtil.parseToken(token);
        if (tokenItem == null) {
            log.error("没有找到token= {} 对应信息",token);
            return ErrorEnum.PARAMETER_ERROR.getResult();
        }
        request.setAttribute("userId",tokenItem.getUserId());
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        log.info("请求开始, url: {}, method: {}, uri: {}, params: {}", url, method, uri, pjp.getArgs());

        // result的值就是被拦截方法的返回值
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        long continueTime = end - start;
        if(continueTime / 1000 > 0){
            log.info("接口执行了 {} 毫秒",continueTime);
        }

        Gson gson = new Gson();
        log.info("请求结束，controller的返回值是 " + gson.toJson(result));
        return result;
    }
}
